﻿using DeepZoom;
using IndexedFilePackageLibrary;
using System;
using System.IO;

namespace VirtualSlideViewer.TileSources
{
    class DeepZoomIfpTileSource : DeepZoomImageTileSource
    {
        public DeepZoomIfpTileSource(Uri sourceUri) : base(sourceUri)
        {
        }

        public override object GetTileLayers(int tileLevel, int tilePositionX, int tilePositionY)
        {
            if (!TileExists(tileLevel, tilePositionX, tilePositionY))
                return null;

            var source = UriSource.OriginalString;
            var ifpPath = source.Substring(0, source.Length - 4) + "_files.ifp";
            var fileName = GetTileFileLocation(tileLevel, tilePositionX, tilePositionY);
            if (!File.Exists(ifpPath))
            {
                return null;
            }
            var package = IndexedFilePackage.Open(ifpPath);
            var fileIndex = package.FindFile(fileName);
            if (fileIndex == null)
            {
                return null;
            }
            return package.SwitchToFileStream(fileIndex);
        }
    }
}
